<template>
    <div class="box-content">
        <vxe-toolbar ref="toolbarRef" v-bind="toolbarConfig">
            <template #buttons>
                <template v-for="(btn,index) in toolbarConfig.btns" :key="index">
                    <el-button @click="btn.click()" type="primary" v-bind="btn.config"
                               :icon="typeof (btn.icon) === 'function'? btn.icon() : ''">
                        {{ btn.label }}
                    </el-button>
                </template>
                <component v-if="toolbarConfig.render" :is="toolbarConfig.render()"></component>
                <div v-if="isSearch" style="flex-grow: 1;">
                    <base-form :style="toolbarConfig.btns.length ? 'float:right': 'float:left'"
                               :filter-config="formConfig" :filter-form="formData"
                               @get-form-value="getFormValues"></base-form>
                </div>

            </template>
        </vxe-toolbar>
        <div class="table-content">
            <vxe-table
                    border="none"
                    stripe
                    :height="tableHeight"
                    keep-source
                    show-overflow
                    :sort-config="sortConfig"
                    :id="router.currentRoute.value.name"
                    ref="baseTable"
                    :print-config="printConfig"
                    :data="tableData"
                    :column-config="{ resizable: true,useKey:true,isCurrent:false}"
                    :row-config="{useKey:true,isCurrent:true,height:48,keyField:'rowId'}"
                    :auto-resize="true"
                    :sync-resize="true"
                    size="small"
                    :edit-config="{trigger: 'click', mode: 'cell', showStatus: true}"
                    :edit-rules="editRules"
                    :loading="loading"
                    v-bind="tableConfig"
                    show-header-overflow="ellipsis"
                    @sort-change="handlerSortChange"
                    @filter-change="handleFilterNameMethod"
                    @cell-click="handlRowClick"
                    @checkbox-change="handleSelectionChange"
                    @checkbox-all="handleAllSelection"
                    @cell-dblclick="handlRowDblclick"
                    @current-change="currentChangeEvent"
                    @custom="handleCustom"
                    :footerMethod="footerMethod"
                    :merge-footer-items="mergeFooterItems"
					@scroll="handleScroll"
            >
                <template v-for="(group,index) in colgroups" v-if="colgroups.length" :key="index">
                    <vxe-colgroup :header-align="group.align || 'left'" :resizable="true"  v-if="group.isGroup" v-bind="group.config">
                        <template v-for="(item,colIndex) in group.columns" :key="colIndex">
                            <column-item :item="item"></column-item>
                        </template>
                        <template #header="slotParams">
                            <component :is="group.titleRender(slotParams)"  v-if="group.titleRender"></component>
                            <div v-else>{{group.title}}</div>
                        </template>
                    </vxe-colgroup>
                    <column-item :item="group" v-if="!group.isGroup"></column-item>
                </template>
                <template v-for="(item,index) in columns" :key="index" v-if="!colgroups.length">
                    <column-item :item="item"></column-item>
                </template>
                <template #empty>
                <span style="color: #222222;font-size: 16px">
                  <p>{{ emptyText }}</p>
                </span>
                </template>
            </vxe-table>
            <slot name="footerSlot"></slot>
            <div style="width: 100%;text-align: right;" v-if="pagination.page">
                <!-- <div>{{pagination[paginationProps.size]}}</div> -->
                <el-pagination
                        style="float:right; height: 36px;"
                        :current-page="pagination.page[paginationProps.current]"
                        :page-size="pagination.page[paginationProps.size]"
                        :page-sizes="pageSize"
                        :total="pagination.total || 0"
                        layout="total, sizes, prev, pager, next, jumper"
                        @size-change="handlSizeChange"
                        @current-change="handlcurrentChange"
                        background
                        small
                ></el-pagination>
            </div>
        </div>
    </div>
</template>

<script setup>
import {defineProps, defineEmits, reactive, nextTick, ref, onMounted, h, unref, toRefs, guardReactiveProps} from "vue"
import 'vxe-table/lib/style.css'
import BaseForm from "@/components/BaseForm/BaseForm.vue";
import {useRouter} from "vue-router";
import ColumnItem from "@/components/BaseTable/ColumnItem.vue";

const toolbarRef = ref()
const popoverRef = ref(null)

let emit = defineEmits(['filter-method', 'on-click', 'on-multiple-select', 'on-all-multiple-select', 'update:row-determine', 'on-custom', 'update: rowdecide', 'on-update-forms', 'on-refs'])
let props = defineProps({
    // 工具栏配置
    toolbarConfig: {
        type: Object,
        default: () => {
            return {
                btns: [],
            }
        }
    },
    // 是否需要搜索栏
    isSearch: {
        type: Boolean,
        default: true
    },
    sortConfig: {
        type: Object,
        default: () => {
            return {multiple: false}
        }
    },
    // 表单配置
    formConfig: {
        type: Object,
        default: () => {
            return {
                elForm: {},
                typeSetting: []
            }
        },
    },
    // 表单v-model值绑定
    formData: {
        type: Object,
        default: () => {
        }
    },
    // 打印配置
    printConfig: {
        type: Object,
        default: () => {
        }
    },
    loading: {
        type: Boolean,
        default: () => false,
    },
    // 表格配置
    tableConfig: {
        type: Object,
        default: () => {
        }
    },
    // 表格配置
    editRules: {
        type: Object,
        default: () => []
    },
    // 表格数据
    tableData: {
        type: Array,
        default: () => []
    },
    // 表格头
    columns: {
        type: Array,
        default: () => []
    },
    // 分组表头
    colgroups: {
        type: Array,
        default: () => []
    },
    // 表格数据加载方法
    select: Function,
    // 表格排序方法
    sortMethod: Function,
    // 表格底部合计
    footerMethod: Function,
    // 表格底部合并
    mergeFooterItems: Array,
    // 表格分页
    pagination: {
        type: Object,
        default: () => ({
            page: null,
            total: 1,
        }),
    },
    // 表格分页Props
    paginationProps: {
        type: Object,
        default: () => {
            return {
                current: "current",
                size: 'size',
            }
        }
    },
    // 表格分页条数设置
    pageSize: {
        type: Array,
        default: () => {
            return [10, 20, 50, 100]
        }
    },
    operationBtn: {
        type: Array,
        default: () => []
    },
    isClickRow: {
        type: Boolean,
        default: true,
    },
    isShowOptions: Function,
    //表格舍弃高度
    reduceHeight: {
        type: Number,
        default: () => 220
    },
    // 空数据提示文本
    emptyText: {
        type: String,
        default: () => "暂无数据！"
    }
})
const baseTable = ref()
let router = useRouter()
const state = reactive({
    defTableData: [],
    tableHeight: 500,
    clickRowIndex: 0,
    clickRow: {},
})

// 排序
const handlerSortChange = (e) => {
    let fields = [];
    let orders = []
    if (props.sortConfig.multiple && e.sortList.length) {
        fields = e.sortList.map(item => item.field)
        orders = e.sortList.map(item => item.order)
    }
    props.pagination.orderBy = fields.length ? fields.join(',') : e.order ? e.field : null;
    props.pagination.rule = orders.length ? orders.join(',') : e.order;
    if (props.sortMethod) {
        props.sortMethod(e);
    } else {
        props.select();
    }
};
const getFormValues = (e) => {
    emit('on-update-forms', e)
}
// 筛选数据
const handleFilterNameMethod = ({values, field}) => {
    emit("filter-method", {values, field});
};
const pageX = ref(null)
const pageY = ref(null)
const clickValue = ref(false)
const clickRow = ref({})
// 单击
const handlRowClick = (e) => {
    // 单机跟随操作弹窗
    let value = props.isShowOptions ? (props.isShowOptions({
        item: e.row,
        rowIndex: e._rowIndex,
        type: "click"
    }) && props.isClickRow) : props.isClickRow
    if (value) {
        pageX.value = e.$event.pageX
        pageY.value = e.$event.pageY
        clickValue.value = !clickValue.value
        clickRow.value = e.row
        state.clickRow = clickRow.value
        state.clickRowIndex = e.rowIndex
    } else {
        clickValue.value = false
    }
    emit("on-click", {item: e.row, rowIndex: e._rowIndex, type: "click"});
};
// 选择框改变
const handleSelectionChange = (val) => {
    if (val) {
        state.defTableData = props.tableData;
    }
    emit('on-multiple-select', val)
};
// 多选
const handleAllSelection = (val) => {
    emit('on-all-multiple-select', val)
};
// 双击
const handlRowDblclick = (e) => {
    emit("on-click", {item: e.row, type: "dblclick"});
};
// 选中当前行
const currentChangeEvent = (row) => {
    state.thisActiveRow = row;
    emit("update:row-determine", row);
};
// 自定义表格选择事件
const handleCustom = (e) => {
    emit('on-custom', e)
}
const handlSizeChange = (e) => {
    state.isSizeChange = true;
    props.pagination.page[props.paginationProps.size] = e;
    props.pagination.page[props.paginationProps.current] = 1;
    if (props.select) {
        props.select();
        nextTick(() => {
            state.isSizeChange = false;
        });
    }
};
const handlcurrentChange = (e) => {
    if (state.isSizeChange) {
        return;
    }
    props.pagination.page[props.paginationProps.current] = e;
    if (props.select) {
        props.select();
    }
};
const onClickOutside = () => {
    unref(popoverRef).popperRef?.delayHide?.()
}
const handleOperationClick = (item) => {
    setTimeout(()=>{
        clickValue.value = false
    },500)
    item.click(clickRow.value, state.clickRowIndex)
}
const handleChangWindowHeight = () => {
    state.tableHeight = document.body.clientHeight - props.reduceHeight
}
//表格华滑动
const handleScroll=(e)=>{
	
	if(e.isY){
		if(clickValue.value){
			clickValue.value = false
		}
	}
}
onMounted(() => {
    handleChangWindowHeight()
    nextTick(() => {
        baseTable.value.connect(toolbarRef.value)
        window.addEventListener("resize", handleChangWindowHeight);
        emit('on-refs', baseTable.value)
    })
})
const {tableHeight} = toRefs(state)
defineExpose({
    baseTable,
    state,
    props,
    router,
    clickValue,
    pageX,
    pageY,
    handlRowClick,
    handleSelectionChange,
    handleAllSelection,
    handlRowDblclick,
    currentChangeEvent,
    handleCustom,
    handlSizeChange,
    handlcurrentChange,
    onClickOutside,
    handleOperationClick,
    tableHeight,
    handlerSortChange,
    getFormValues,
    handleFilterNameMethod,
    clickRow,
})
</script>

<style lang="scss" scoped>
.vxe-toolbar {
  background: none;

  :deep(.el-form-item) {
    margin-bottom: 0;
  }

  :deep(.el-input__wrapper) {
    border: 1.5px solid #000;
    background: none;
    font-size: 16px;
  }
  
  :deep(.el-input) {
    --el-input-placeholder-color: #666
  }

  :deep(.el-input__icon) {
    color: #000
  }
}
:deep(.el-pagination.is-background .el-pager li ){
    border-radius:50% ;
    width: 36px;
    height: 36px;
}
:deep(.el-pagination--small .el-select .el-input){
    height: 36px;
}
.table-content {
  background: #fff;
  border-radius: 20px;
  padding: 12px;
  // overflow: hidden;
  overflow: auto;
}

:deep(.el-pagination) {
  margin-top: 12px;

  .el-input__wrapper {
    border-radius: 36px;
    background-color: #F3F3F3;
    height: 36px;
  }

 

  .number {
    border-radius: 50%;
    height: 36px;
    width: 36px;
    color: #000000;
    font-size: 14px;
    background-color: #F3F3F3 ;

  }
  :deep(.el-pagination.is-background .el-pager li){
background-color: #F3F3F3 ;
  }

  .btn-prev {
    border-radius: 50%;
    height: 36px;
    width: 36px;
  }

  .btn-next {
    border-radius: 50%;
    height: 36px;
    width: 36px;
  }
}

.icon-close {
  position: absolute;
  width: 20px;
  right: -9px;
  top: -9px
}

.op-line {
  width: 100%;
  height: 1px;
  background: #F3F3F3;
}

.tabel-option-info {
  position: fixed;
  display: inline-flex;
  padding: 12px 8px;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: 10px;
  border-radius: 16px;
  background: #FFF;
  box-shadow: -2px 2px 10px 0 rgba(12, 38, 140, 0.2);
  width: 32px;
  right: 4px;
  z-index: 9;
  top: 50%;
  margin-top: -120px;
}
:deep(.el-pagination .el-input__inner){
    color: #000000;
}
:deep(.el-pagination>.is-first){
    color: #000000;
}
:deep(.el-input__suffix-.el-select .el-input__wrapper .el-input__suffix .el-input__suffix-inner){
    padding-top:10px !important;
  }
  :deep(.el-input__suffix){
    align-items: center;
  }
  :deep(.el-input__inner){
    font-size: 14px;
  }
  :deep([data-v-bcf8ee74] .el-pagination>.is-first){
    font-size: 14px;
  }
  :deep(.el-button [class*=el-icon]+span){
   font-size: 16px;
  }
  :deep(.el-button.is-round){
    height: 40px;
  }
  :deep(.el-input__wrapper.is-focus){
    border: #FFF solid 1px;
  }
</style>
